package com.viking.util;

import cn.hutool.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Post {

    public boolean inSure=false;
    public Post(String username, char[] password, String code,String checkKey) throws Exception {

        //String url = "http://185.145.244.92:3001/login";
        String url = "http://viking.daxiangcoding.com/jeecg-boot/sys/login/";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        String pass= String.valueOf(password);
        //添加请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        //发送Post请求
        con.setDoOutput(true);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), "UTF-8"));
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("username",username);
        jsonObject.put("password",pass);
        jsonObject.put("remember_me","true");
        jsonObject.put("captcha",code);
        jsonObject.put("checkKey",checkKey);
        writer.write(jsonObject.toString());
        writer.flush();
        writer.close();

        System.out.println(jsonObject.toString());

        int responseCode = con.getResponseCode();
        System.out.println("Sending 'POST' request to URL : " + url);

        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine = null;


        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        in.close();


        Matcher m = Pattern.compile("(?i)\"token\": *\"([^\"]*)\"").matcher(response.toString());
        if(m.find()) {
            System.out.println(m.group(1));
        }
        if(m.group(1)!=null){
            inSure =true;
        }
    }


}
